package com.example.demo.util;

import io.jsonwebtoken.*;
import io.jsonwebtoken.io.Decoders;
import io.jsonwebtoken.security.Keys;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Component;

import java.security.Key;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.function.Function;

@Component
public class JwtUtilsSelf {

    private static Logger logger = LoggerFactory.getLogger(JwtUtilsSelf.class);

    @Value("${jwt.secret}")
    private String secret;

    @Value("${jwt.expiration}")
    private long expiration;

    // 生成JWT令牌
    public String generateToken(UserDetails userDetails) {
        return generateToken(new HashMap<>(), userDetails);
    }

    // 生成带额外声明的JWT令牌
    public String generateToken(Map<String, Object> extraClaims, UserDetails userDetails) {


        Date now = new Date();
        Date expirationDate = new Date(System.currentTimeMillis() + expiration);

        logger.warn("Token generation time: {}", now);
        logger.warn("Token expiration time: {}", expirationDate);
        logger.warn("Current system time: {}", System.currentTimeMillis());
        logger.warn("Current system time: {}", System.currentTimeMillis());
        logger.warn("Current system time: {}", System.currentTimeMillis());
        logger.warn("Current system time: {}", System.currentTimeMillis());
        logger.warn("Current system time: {}", System.currentTimeMillis());
        logger.warn("Current system time end: {}", System.currentTimeMillis() + expiration);

        String token = Jwts.builder()
                .setClaims(extraClaims)
                .setSubject(userDetails.getUsername())
                .setIssuedAt(new Date(System.currentTimeMillis()))
                .setExpiration(new Date(System.currentTimeMillis() + expiration))
                .signWith(getSignInKey(), SignatureAlgorithm.HS256)
                .compact();
        logger.warn("Generated token: {}", token);
        logger.warn("valid time token: {}", extractExpiration(token));
        logger.warn("name token: {}", extractUsername(token));
        logger.warn("是否过期 token: {}", isTokenExpired(token));
        return token;
    }

    // 验证JWT令牌
    public boolean isTokenValid(String token, UserDetails userDetails) {
        final String username = extractUsername(token);
        return (username.equals(userDetails.getUsername())) && !isTokenExpired(token);
    }

    // 提取JWT中的用户名
    public String extractUsername(String token) {
        return extractClaim(token, Claims::getSubject);
    }

    // 提取JWT中的过期时间
    private Date extractExpiration(String token) {
        return extractClaim(token, Claims::getExpiration);
    }

    // 提取JWT中的单个声明
    private <T> T extractClaim(String token, Function<Claims, T> claimsResolver) {
        final Claims claims = extractAllClaims(token);
        return claimsResolver.apply(claims);
    }

    // 提取JWT中的所有声明
    private Claims extractAllClaims(String token) {
        logger.warn("token err: {}", token);
        return Jwts.parserBuilder()
                .setSigningKey(getSignInKey())
                .build()
                .parseClaimsJws(token)
                .getBody();
    }

    // 检查JWT是否过期
    private boolean isTokenExpired(String token) {
        return extractExpiration(token).before(new Date());
    }

    // 获取签名密钥
    private Key getSignInKey() {
        System.out.println("=============== error ===============");
        System.out.println("=============== error ===============");
        System.out.println("=============== error ===============");
        System.out.println("=============== error ===============");
        System.out.println("=============== error ===============");
        byte[] keyBytes = Decoders.BASE64.decode(secret);
        return Keys.hmacShaKeyFor(keyBytes);
    }
}